package com.wswy.wzcx.ui.main.home

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.ColorUtils
import android.support.v4.util.SparseArrayCompat
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.widget.FrameLayout
import com.wswy.wzcx.R
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.UserDataProvider
import com.wswy.wzcx.ui.car.AddCarPreActivity
import com.wswy.wzcx.ui.car.remind.RemindActivity
import com.wswy.wzcx.ui.car.result.QueryResultActivity
import com.wswy.wzcx.ui.other.ClickUtils
import com.wswy.wzcx.utils.UiUtils
import com.wswy.wzcx.widget.home.AddCarLayout
import com.wswy.wzcx.widget.home.CarInfoLayout
import com.wswy.wzcx.widget.home.IHomeCarLayout
import com.wswy.wzcx.widget.shadow.ShadowView
import timber.log.Timber
import java.lang.ref.WeakReference
import java.util.*
import kotlin.math.abs
import kotlin.math.max

@SuppressLint("ClickableViewAccessibility")
class HomeCarController (private val viewPager: ViewPager,
                         private val flCars:FrameLayout):View.OnClickListener{


    companion object {
        private const val TAG = "HomeCarController"
    }

    private val context = viewPager.context


    private val bgViews = arrayOf(flCars.findViewById<View>(R.id.img_car_bg_1),
            flCars.findViewById<View>(R.id.img_car_bg_2),
            flCars.findViewById<View>(R.id.img_car_bg_3))

    private val colors = arrayOf(ContextCompat.getColor(context, R.color.accentColor1_50),
            ContextCompat.getColor(context,R.color.accentColor2_50),
            ContextCompat.getColor(context,R.color.accentColor3_50))

    private val flCarsLayout = flCars.findViewById<FrameLayout>(R.id.fl_car_container)
    private val mTouchSlop = ViewConfiguration.get(context).scaledPagingTouchSlop

    private var touchViewRef : WeakReference<View?>? = null
    //private val imgRefresh = flCars.findViewById<ImageView>(R.id.img_refresh)

     init {
        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                //Log.e(TAG, " --> $positionOffset");


            }

            override fun onPageSelected(position: Int) {

                flShadow.setShadowColor(colors[getColorOffset(position)])

            }

        })

        viewPager.setOnTouchListener(object :View.OnTouchListener{
            private var touchClickFlag = false
            private var x = 0f
            private var y = 0f

            override fun onTouch(v: View?, event: MotionEvent?): Boolean {

                //Timber.e("viewPager event-->  $event")
                when(event?.action){
                    MotionEvent.ACTION_DOWN -> {
                        touchClickFlag = true
                        x = event.x
                        y = event.y
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val xDiff = Math.abs(event.x - x)
                        val yDiff = Math.abs(event.y - y)
                        //事件滑动的范围判断是否点击
                        touchClickFlag = xDiff < mTouchSlop && yDiff < mTouchSlop

                    }
                    MotionEvent.ACTION_UP -> {

                        //释放时判断是否点击
                        if (touchClickFlag){
                            touchClickFlag = false

                            //如果是点击，获取点击的只view 或者获取当前itemView，发送点击事件

                            val touchView = touchViewRef?.get()
                            val count = viewPager.adapter?.count?:0

                            //更好的处理
                            val view = if((touchView == null || touchView is AddCarLayout) && count > 1 && viewPager.currentItem < count-1){
                                //如果是添加，并且有数据，更正点击事件
                                viewPager.findViewWithTag(viewPager.currentItem)
                            }else{
                                touchView
                            }

                            //点击
                            view?.let {
                                onClick(it)
                                touchViewRef = null
                                return true
                            }
                        }
                        touchClickFlag = false
                        touchViewRef = null
                    }
                }

                return false
            }

        })

    }

    private fun getColorOffset(position: Int):Int{
        return if (position >= colors.size){
            position %  colors.size
        }else{
            max(position,0)
        }
    }

    lateinit var flShadow : ShadowView

    private val datas = ArrayList<UserCarInfo?>()

    private val animators = SparseArrayCompat<ObjectAnimator>()

    private val stackViews = Stack<View>()

    fun getCount() = datas.size

    fun setData(data: List<UserCarInfo?>?) {

        val size = animators.size()
        for (i in 0 until size) {
            animators.valueAt(i).cancel()
        }
        animators.clear()

        datas.clear()
        data?.run {
            datas.addAll(this)
        }

        showCars(datas)
    }

    fun update(userCarInfo:UserCarInfo?){
        val size = datas.size
        var update = false
        if (userCarInfo != null) {
            for (i in 0 until size) {
                val item = datas[i]
                if (item != null && item.id == userCarInfo.id) {
                    update = true
                    if (!userCarInfo.isError) {
                        datas[i] = userCarInfo
                    }
                    val objectAnimator = animators.get(item.id)

                    objectAnimator?.addListener(object : AnimatorListenerAdapter() {
                        override fun onAnimationRepeat(animation: Animator) {
                            super.onAnimationRepeat(animation)
                            objectAnimator.cancel()
                            animators.remove(item.id)
                        }
                    })
                    break
                }
            }
        }

        if (!update) {
            val i = datas.lastIndexOf(null)
            datas.add(Math.max(i, 0), userCarInfo)
            showCars(datas)
        }else{
            updateCars(datas)
        }

    }

    fun deleteCar(carId:Int){
        val size = datas.size
        for (i in 0 until size) {
            if (datas[i]?.id == carId) {
                datas.removeAt(i)
                break
            }
        }

        showCars(datas)
    }

    private val onChildTouchListener = View.OnTouchListener { v, event ->

        //Timber.e("child event-->  $event")
        //记录点击的view
        if (event?.action == MotionEvent.ACTION_DOWN){
            touchViewRef = WeakReference(v)
        }
        false
    }

    override fun onClick(v: View?) {
        if (ClickUtils.isFastClick()){
            return
        }

        val position = (v?.getTag(R.id.item_position) as? Int)?:-1
        val userCarInfo = datas.getOrNull(position)

        if ( v?.id == R.id.img_refresh) {

            userCarInfo?.run {

                if (animators.get(this.id) == null) {
                    UserDataProvider.get().carFineListRun(this.id)

//                    v.pivotX = (v.width / 2).toFloat()
//                    v.pivotY = (v.height / 2).toFloat()

                    val animator = ObjectAnimator.ofFloat(v, View.ROTATION, v.rotation, v.rotation + 360)
                    //animator.interpolator = LinearInterpolator()
                    animator.repeatCount = ObjectAnimator.INFINITE
                    animator.repeatMode = ObjectAnimator.RESTART
                    animator.duration = 1200
                    animator.start()

                    animators.put(this.id, animator)
                }

            }


        } else if (v?.id == R.id.layout_info_1 && userCarInfo != null){

            QueryResultActivity.start(context, userCarInfo, -1)
        } else if (v?.id == R.id.layout_info_2 && userCarInfo != null){
            RemindActivity.startInspection(context,userCarInfo)
        } else if (v?.id == R.id.layout_info_3 && userCarInfo != null){
            RemindActivity.startValuation(context,userCarInfo)

        } else {

            if (userCarInfo == null) {
                context.startActivity(Intent(context, AddCarPreActivity::class.java))
                //AddEditLicenseActivity.startAdd(context,pos);
            } else if (position >=0){
                QueryResultActivity.start(context, userCarInfo, position)
            }
        }

    }

    private fun recycler(){
        val layout = flCarsLayout

//        for (i in 0 until layout.childCount){
//
//            layout.getChildAt(i)?.apply {
//                isSelected = false
//                isPressed = false
//                tag = null
//
//                clearFocus()
//                clearAnimation()
//
//
//                setOnClickListener(null)
//
//                if(this is CarInfoLayout){
//                    stackViews.push(this)
//                }
//
//            }
//        }

        //layout.removeAllViews()
        layout.removeAllViewsInLayout()

    }

    private fun obtainView():CarInfoLayout{
        if (!stackViews.isEmpty()){
            (stackViews.pop() as? CarInfoLayout)?.apply {
                return this
            }
        }
        return CarInfoLayout(context)
    }


    private fun updateCars(cars:List<UserCarInfo?>){
        val layout = flCarsLayout
        for (i in 0 until layout.childCount){
            (layout.getChildAt(i) as? CarInfoLayout)?.run {

                cars.getOrNull(i)?.let {
                    setData(it)
                }

            }
        }
    }

    private fun showCars(cars:List<UserCarInfo?>){
        val views = arrayListOf<IHomeCarLayout>()

        recycler()

        cars.forEachIndexed { index, item ->

            item?.let {
                CarInfoLayout(context).apply {
                    setData(item)

                    //以触摸事件传递点击
                    findViewById<View>(R.id.img_refresh)?.let {
                        it.setTag(R.id.item_position,index)
                        it.setOnTouchListener(onChildTouchListener)
                    }

                    //查违章
                    findViewById<View>(R.id.layout_info_1)?.let {
                        it.setTag(R.id.item_position,index)
                        it.setOnTouchListener(onChildTouchListener)
                    }
                    //年检
                    findViewById<View>(R.id.layout_info_2)?.let {
                        it.setTag(R.id.item_position,index)
                        it.setOnTouchListener(onChildTouchListener)
                    }
                    //估值
                    findViewById<View>(R.id.layout_info_3)?.let {
                        it.setTag(R.id.item_position,index)
                        it.setOnTouchListener(onChildTouchListener)
                    }

                    flCarsLayout.addView(this)
                    views.add(this)
                    alpha = 0f

                    if (index == 0){
                        alpha = 1f
                    }

                    if (index > 0){
                        hideRight()
                    }
                }
            }?:kotlin.run {
                AddCarLayout(context).apply {
                    flCarsLayout.addView(this)

                    setTag(R.id.item_position,Int.MAX_VALUE)

                    setOnTouchListener(onChildTouchListener)

                    views.add(this)

                    alpha = 0f

                    if (index > 0){
                        hideRight()
                    }
                    if (index == 0){
                        alpha = 1f
                    }
                }
            }


        }

        viewPager.setPageTransformer(false) { page, position ->

            //Log.e(TAG, " setPageTransformer -->  ${page.tag}  $position");
            val p = (page.tag as? Int) ?: -1

            val view = views[p]

            if (position < -1) { //(-Infinity,-1)
                //左
                //view.translationX = -page.width * 1f
                view.alpha(0f)
                view.hideLeft()

            } else if (position <= 1) { // [-1,1]

                //Log.e(TAG, "offset --> $p $position ");

                view.animOffset(position)

                val op = p % bgViews.size




                if (position < 0) { // (0,-1]


                    //[0 -> -1] 隐藏到左边
                    //[-1 -> 0] 从左边出来
                    view.alpha(1 + position)

                    bgViews[op].alpha = 1+position


                    //Log.e(TAG, "左边 --> $p  $position");

                    //view.animOffset(1+position)

                    if (1+position == 0f){
                        view.hideLeft()
                    }

                    if (p == viewPager.currentItem){
                        //

                        //Log.e(TAG, " --> to left $p  $position");
                        flShadow.setShadowColor(ColorUtils.blendARGB(colors[getColorOffset(p)],colors[getColorOffset(p+1)],abs(position)))

                    }

                } else { // [1,0)
                    //右边
                    //view.animOffset(1-position)
                    view.alpha(1 - position)


                    bgViews[op].alpha = 1 - position

                    if (1-position == 0f){
                        view.hideRight()
                    }

                    if (p == viewPager.currentItem){
                        //

                        //Log.e(TAG, " -->to right $p  $position");

                        flShadow.setShadowColor(ColorUtils.blendARGB(colors[getColorOffset(p)],colors[getColorOffset(p-1)],position))

                    }

                    //[1 -> 0] 从右边进来
                    //[0 -> 1] 隐藏到右边

                }

            } else { //(1,+Infinity]
                //view.translationX = page.width * 2f
                view.alpha(0f)

                view.hideRight()
            }

        }

        //viewPager.offscreenPageLimit = 3

        viewPager.adapter = object : PagerAdapter() {
            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun getCount(): Int = cars.size

            override fun instantiateItem(container: ViewGroup, position: Int): Any {

                return View(context).also {
                    it.tag = position

                    //it.setOnClickListener(this@HomeCarController)
                    //it.setTag(R.id.item_data,cars[position])
                    it.setTag(R.id.item_position,position)
                    container.addView(it, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                }
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                //super.destroyItem(container, position, `object`)

                (`object` as? View)?.run {
                    container.removeView(this)
                }

            }

        }

        UiUtils.addOnGlobalLayoutListener(views[0].getView()){
            views[0].animOffset(0f)
        }


        bgViews.forEachIndexed { index, view ->

            view.alpha = if (index == 0) 1f else 0f
        }
    }

}